<template>
  <div class="mock-example">
    <div class="header">
      <h2>🎭 Mock 数据使用示例</h2>
      <div class="mock-status">
        <span class="status-badge" :class="mockStatusClass">
          {{ mockStatusText }}
        </span>
      </div>
    </div>

    <!-- 用户管理示例 -->
    <div class="section">
      <h3>👥 用户管理</h3>
      <div class="controls">
        <el-button @click="fetchUsers" :loading="loading.users">
          获取用户列表
        </el-button>
        <el-button @click="createUser" type="primary">
          创建用户
        </el-button>
        <el-button @click="getUserStats" type="success">
          获取统计
        </el-button>
      </div>
      
      <div v-if="userList.length > 0" class="data-display">
        <el-table :data="userList" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="role" label="角色" width="100">
            <template #default="{ row }">
              <el-tag :type="getRoleType(row.role)">{{ row.role }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 0 ? 'success' : 'danger'">
                {{ row.status === 0 ? '正常' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 案件管理示例 -->
    <div class="section">
      <h3>📋 案件管理</h3>
      <div class="controls">
        <el-button @click="fetchCases" :loading="loading.cases">
          获取案件列表
        </el-button>
        <el-button @click="createCase" type="primary">
          创建案件
        </el-button>
        <el-button @click="getCaseStats" type="success">
          获取统计
        </el-button>
      </div>
      
      <div v-if="caseList.length > 0" class="data-display">
        <el-table :data="caseList" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="category" label="类别" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getCaseStatusType(row.status)">
                {{ getCaseStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="进度" width="120">
            <template #default="{ row }">
              <el-progress :percentage="row.progress" />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 律师管理示例 -->
    <div class="section">
      <h3>⚖️ 律师管理</h3>
      <div class="controls">
        <el-button @click="fetchLawyers" :loading="loading.lawyers">
          获取律师列表
        </el-button>
        <el-button @click="createLawyer" type="primary">
          创建律师
        </el-button>
        <el-button @click="getLawyerStats" type="success">
          获取统计
        </el-button>
      </div>
      
      <div v-if="lawyerList.length > 0" class="data-display">
        <el-table :data="lawyerList" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="specialties" label="专业领域" width="200">
            <template #default="{ row }">
              <el-tag 
                v-for="specialty in row.specialties" 
                :key="specialty"
                size="small"
                style="margin-right: 4px"
              >
                {{ specialty }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="rating" label="评分" width="100">
            <template #default="{ row }">
              <el-rate :value="row.rating" disabled />
            </template>
          </el-table-column>
          <el-table-column prop="available" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.available ? 'success' : 'warning'">
                {{ row.available ? '空闲' : '忙碌' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 认证示例 -->
    <div class="section">
      <h3>🔐 认证功能</h3>
      <div class="auth-form">
        <el-form :model="loginForm" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="loginForm.username" placeholder="输入用户名" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              placeholder="输入密码"
              show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="login" type="primary" :loading="loading.login">
              登录
            </el-button>
            <el-button @click="getCurrentUser">获取当前用户</el-button>
            <el-button @click="logout">登出</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 错误处理示例 -->
    <div class="section">
      <h3>⚠️ 错误处理</h3>
      <div class="controls">
        <el-button @click="testError" type="warning">
          测试错误响应
        </el-button>
        <el-button @click="testSlow" type="info">
          测试慢速响应
        </el-button>
        <el-button @click="testNetworkError" type="danger">
          测试网络错误
        </el-button>
      </div>
    </div>

    <!-- 功能测试 -->
    <div class="section">
      <h3>🧪 功能测试</h3>
      <div class="controls">
        <el-button @click="runFullTests" type="primary" :loading="testing">
          运行完整测试
        </el-button>
        <el-button @click="clearLogs" type="info">
          清空日志
        </el-button>
      </div>
      
      <div v-if="testResults.total > 0" class="test-results">
        <h4>测试结果</h4>
        <div class="result-summary">
          <el-tag type="success">通过: {{ testResults.passed }}</el-tag>
          <el-tag type="danger">失败: {{ testResults.failed }}</el-tag>
          <el-tag type="info">成功率: {{ testResults.successRate }}%</el-tag>
        </div>
      </div>
    </div>

    <!-- 日志显示 -->
    <div class="section">
      <h3>📝 操作日志</h3>
      <div class="log-container">
        <div 
          v-for="(log, index) in logs" 
          :key="index" 
          :class="['log-item', log.type]"
        >
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '@/utils/request';
import { runAllTests } from '@/utils/mock-test.js';

// 响应式数据
const userList = ref([]);
const caseList = ref([]);
const lawyerList = ref([]);
const logs = ref([]);

const loading = reactive({
  users: false,
  cases: false,
  lawyers: false,
  login: false
});

const testing = ref(false);
const testResults = ref({
  total: 0,
  passed: 0,
  failed: 0,
  successRate: 0
});

const loginForm = reactive({
  username: 'testuser',
  password: '123456'
});

// 计算属性
const mockStatusText = computed(() => {
  return import.meta.env.DEV ? '开发环境' : '生产环境';
});

const mockStatusClass = computed(() => {
  return import.meta.env.DEV ? 'dev' : 'prod';
});

// 工具函数
const addLog = (message, type = 'info') => {
  logs.value.unshift({
    time: new Date().toLocaleTimeString(),
    message,
    type
  });
  
  // 限制日志数量
  if (logs.value.length > 50) {
    logs.value = logs.value.slice(0, 50);
  }
};

const getRoleType = (role) => {
  const types = {
    admin: 'danger',
    lawyer: 'warning',
    user: 'info'
  };
  return types[role] || 'info';
};

const getCaseStatusType = (status) => {
  const types = {
    0: 'info',    // 待受理
    1: 'warning', // 处理中
    2: 'success', // 已完成
    3: 'danger',  // 已拒绝
    4: 'info'     // 已取消
  };
  return types[status] || 'info';
};

const getCaseStatusText = (status) => {
  const texts = {
    0: '待受理',
    1: '处理中',
    2: '已完成',
    3: '已拒绝',
    4: '已取消'
  };
  return texts[status] || '未知';
};

// API 调用函数
const fetchUsers = async () => {
  loading.users = true;
  try {
    const response = await api.get('/users', {
      params: { page: 1, size: 10 }
    });
    userList.value = response.data || response;
    addLog(`获取用户列表成功，共 ${userList.value.length} 条数据`, 'success');
  } catch (error) {
    addLog(`获取用户列表失败: ${error}`, 'error');
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.users = false;
  }
};

const createUser = async () => {
  try {
    const newUser = {
      username: `user_${Date.now()}`,
      name: `测试用户${Date.now()}`,
      email: `test${Date.now()}@example.com`,
      phone: '13800138000',
      role: 'user'
    };
    
    const response = await api.post('/users', newUser);
    addLog(`创建用户成功: ${newUser.name}`, 'success');
    ElMessage.success('用户创建成功');
    
    // 刷新用户列表
    await fetchUsers();
  } catch (error) {
    addLog(`创建用户失败: ${error}`, 'error');
    ElMessage.error('创建用户失败');
  }
};

const getUserStats = async () => {
  try {
    const response = await api.get('/users/stats');
    addLog(`获取用户统计成功: 总数 ${response.total}`, 'success');
    ElMessage.success(`用户总数: ${response.total}`);
  } catch (error) {
    addLog(`获取用户统计失败: ${error}`, 'error');
    ElMessage.error('获取用户统计失败');
  }
};

const fetchCases = async () => {
  loading.cases = true;
  try {
    const response = await api.get('/cases', {
      params: { page: 1, size: 10 }
    });
    caseList.value = response.data || response;
    addLog(`获取案件列表成功，共 ${caseList.value.length} 条数据`, 'success');
  } catch (error) {
    addLog(`获取案件列表失败: ${error}`, 'error');
    ElMessage.error('获取案件列表失败');
  } finally {
    loading.cases = false;
  }
};

const createCase = async () => {
  try {
    const newCase = {
      title: `测试案件${Date.now()}`,
      description: '这是一个测试案件',
      category: '民事纠纷',
      applicantName: '测试申请人',
      applicantPhone: '13800138000',
      budget: 5000
    };
    
    const response = await api.post('/cases', newCase);
    addLog(`创建案件成功: ${newCase.title}`, 'success');
    ElMessage.success('案件创建成功');
    
    // 刷新案件列表
    await fetchCases();
  } catch (error) {
    addLog(`创建案件失败: ${error}`, 'error');
    ElMessage.error('创建案件失败');
  }
};

const getCaseStats = async () => {
  try {
    const response = await api.get('/cases/stats');
    addLog(`获取案件统计成功: 总数 ${response.total}`, 'success');
    ElMessage.success(`案件总数: ${response.total}`);
  } catch (error) {
    addLog(`获取案件统计失败: ${error}`, 'error');
    ElMessage.error('获取案件统计失败');
  }
};

const fetchLawyers = async () => {
  loading.lawyers = true;
  try {
    const response = await api.get('/lawyers', {
      params: { page: 1, size: 10 }
    });
    lawyerList.value = response.data || response;
    addLog(`获取律师列表成功，共 ${lawyerList.value.length} 条数据`, 'success');
  } catch (error) {
    addLog(`获取律师列表失败: ${error}`, 'error');
    ElMessage.error('获取律师列表失败');
  } finally {
    loading.lawyers = false;
  }
};

const createLawyer = async () => {
  try {
    const newLawyer = {
      username: `lawyer_${Date.now()}`,
      name: `测试律师${Date.now()}`,
      email: `lawyer${Date.now()}@example.com`,
      phone: '13800138000',
      specialties: ['民事纠纷'],
      experience: 5,
      hourlyRate: 200
    };
    
    const response = await api.post('/lawyers', newLawyer);
    addLog(`创建律师成功: ${newLawyer.name}`, 'success');
    ElMessage.success('律师创建成功');
    
    // 刷新律师列表
    await fetchLawyers();
  } catch (error) {
    addLog(`创建律师失败: ${error}`, 'error');
    ElMessage.error('创建律师失败');
  }
};

const getLawyerStats = async () => {
  try {
    const response = await api.get('/lawyers/stats');
    addLog(`获取律师统计成功: 总数 ${response.total}`, 'success');
    ElMessage.success(`律师总数: ${response.total}`);
  } catch (error) {
    addLog(`获取律师统计失败: ${error}`, 'error');
    ElMessage.error('获取律师统计失败');
  }
};

const login = async () => {
  loading.login = true;
  try {
    const response = await api.post('/auth/login', loginForm);
    addLog(`登录成功: ${response.user?.name}`, 'success');
    ElMessage.success('登录成功');
    
    // 保存token
    localStorage.setItem('token', response.token);
  } catch (error) {
    addLog(`登录失败: ${error}`, 'error');
    ElMessage.error('登录失败');
  } finally {
    loading.login = false;
  }
};

const getCurrentUser = async () => {
  try {
    const response = await api.get('/auth/current-user');
    addLog(`获取当前用户成功: ${response.name}`, 'success');
    ElMessage.success(`当前用户: ${response.name}`);
  } catch (error) {
    addLog(`获取当前用户失败: ${error}`, 'error');
    ElMessage.error('获取当前用户失败');
  }
};

const logout = async () => {
  try {
    await api.post('/auth/logout');
    localStorage.removeItem('token');
    addLog('登出成功', 'success');
    ElMessage.success('登出成功');
  } catch (error) {
    addLog(`登出失败: ${error}`, 'error');
    ElMessage.error('登出失败');
  }
};

const testError = async () => {
  try {
    await api.get('/non-existent-endpoint');
  } catch (error) {
    addLog(`错误测试完成: ${error}`, 'warning');
    ElMessage.info('错误测试完成');
  }
};

const testSlow = async () => {
  try {
    const startTime = Date.now();
    await api.get('/users');
    const endTime = Date.now();
    addLog(`慢速测试完成，耗时: ${endTime - startTime}ms`, 'warning');
    ElMessage.info(`请求耗时: ${endTime - startTime}ms`);
  } catch (error) {
    addLog(`慢速测试失败: ${error}`, 'error');
    ElMessage.error('慢速测试失败');
  }
};

const testNetworkError = async () => {
  try {
    // 模拟网络错误
    await api.get('/network-error');
  } catch (error) {
    addLog(`网络错误测试完成: ${error}`, 'error');
    ElMessage.info('网络错误测试完成');
  }
};

// 运行完整测试
const runFullTests = async () => {
  testing.value = true;
  addLog('开始运行完整功能测试...', 'info');
  
  try {
    const results = await runAllTests();
    
    testResults.value = {
      total: results.passed + results.failed,
      passed: results.passed,
      failed: results.failed,
      successRate: ((results.passed / (results.passed + results.failed)) * 100).toFixed(1)
    };
    
    addLog(`测试完成: 通过 ${results.passed} 项，失败 ${results.failed} 项`, 
           results.failed === 0 ? 'success' : 'warning');
    
    if (results.failed === 0) {
      ElMessage.success('所有功能测试通过！');
    } else {
      ElMessage.warning(`部分测试失败，请查看日志`);
    }
  } catch (error) {
    addLog(`测试执行失败: ${error}`, 'error');
    ElMessage.error('测试执行失败');
  } finally {
    testing.value = false;
  }
};

// 清空日志
const clearLogs = () => {
  logs.value = [];
  testResults.value = {
    total: 0,
    passed: 0,
    failed: 0,
    successRate: 0
  };
  addLog('日志已清空', 'info');
};

// 组件挂载时初始化
onMounted(() => {
  addLog('Mock 示例组件已加载', 'info');
});
</script>

<style scoped>
.mock-example {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
}

.header h2 {
  margin: 0;
  color: #333;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.dev {
  background: #e8f5e8;
  color: #2e7d32;
}

.status-badge.prod {
  background: #ffebee;
  color: #c62828;
}

.section {
  margin-bottom: 40px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: #fafafa;
}

.section h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
}

.controls {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.data-display {
  margin-top: 20px;
}

.auth-form {
  max-width: 400px;
}

.log-container {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background: #f8f9fa;
  padding: 10px;
}

.log-item {
  display: flex;
  gap: 10px;
  margin-bottom: 8px;
  padding: 6px 10px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.log-item.info {
  background: #e3f2fd;
  color: #1976d2;
}

.log-item.success {
  background: #e8f5e8;
  color: #2e7d32;
}

.log-item.warning {
  background: #fff3e0;
  color: #e65100;
}

.log-item.error {
  background: #ffebee;
  color: #c62828;
}

.log-time {
  font-weight: bold;
  min-width: 80px;
}

.log-message {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .mock-example {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }
  
  .controls {
    flex-direction: column;
  }
  
  .controls .el-button {
    width: 100%;
  }
}
</style> 